import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

class DlChooseticketnumbers extends StatefulWidget {
  DlChooseticketnumbers({
    super.key,
    required this.numberDatas,
    required this.callback,
  });
  List numberDatas;
  Function(Map) callback;
  @override
  State<DlChooseticketnumbers> createState() => _DlChooseticketnumbersState();
}

class _DlChooseticketnumbersState extends State<DlChooseticketnumbers> {
  //
  late List _numberDatas = [];
  late Map _slectedNumberMaps = {};

  void _selectedNumber(String partIndexStr, Map selectingItem) {
    int partIndex = selectingItem['partIndex'];
    int index = selectingItem['index'];

    List PartsArray = _slectedNumberMaps[partIndexStr];
    bool isExist = PartsArray.indexWhere((element) =>
            element['partIndex'] == partIndex && element['index'] == index) !=
        -1;
    if (isExist) {
      PartsArray.removeWhere((element) =>
          element['partIndex'] == partIndex && element['index'] == index);
    } else {
      //数字区选中个数不超过1个
      if (_getPartIndexCountMax(partIndex) >= 1) {
        return;
      }
      PartsArray.add(selectingItem);
    }

    //回调选中的数据
    widget.callback(_slectedNumberMaps);
    setState(() {});
  }

  // 获取当前partIndex的个数
  _getPartIndexCountMax(int partIndex) {
    int count = 0;
    List partsArray = _slectedNumberMaps[partIndex.toString()];
    if (partsArray.isNotEmpty) {
      count = partsArray
          .where((element) => element['partIndex'] == partIndex)
          .length;
    }
    return count;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _numberDatas = widget.numberDatas;
    for (var i = 0; i < DL_Config.digitsStringArr.length; i++) {
      var numMap = {'$i': []};
      _slectedNumberMaps.addAll(numMap);
    }
    print('_slectedNumberMaps--->$_slectedNumberMaps');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      color: Colors.red,
      child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: _numberDatas.length,
          itemBuilder: (context, partIndex) {
            Map element = _numberDatas[partIndex];
            List numbers = element['nums'] ?? [];
            int oddIndex = partIndex % 2;
            Color bgColor =
                oddIndex == 0 ? HexColor('#e6fff0') : HexColor('#ffecf5');
            Color rightNumColor =
                oddIndex == 0 ? HexColor('#168a43') : HexColor('#d22f7d');
            return digitsView(partIndex, numbers,
                bgColor: bgColor, rightNumColor: rightNumColor);
          }),
    );
  }

  Widget digitsView(int partIndex, List numbers,
      {Color bgColor = Colors.white, Color rightNumColor = Colors.white}) {
    List<Widget> rowViews = [];
    for (int i = 0; i < numbers.length; i++) {
      Map element = numbers[i];
      var codeString = element['code'];
      var isRightNum = element['isRight'];
      rowViews.add(rowItem(partIndex, i, codeString, 25.0, 80.0,
          isRight: isRightNum, bgColor: bgColor, rightNumColor: rightNumColor));
    }
    return Container(
      height: 80,
      width: numbers.length * 25.0,
      color: bgColor,
      child: Wrap(
        children: rowViews,
      ),
    );
  }

  Widget rowItem(
      int partIndex, int index, String num, double cellW, double cellH,
      {bool isRight = false,
      Color bgColor = Colors.white,
      Color rightNumColor = Colors.white}) {
    Color _numColor = isRight ? rightNumColor : bgColor;
    Color textColor = isRight ? Colors.white : Colors.black;

    ///查找是否有选中并标记
    if (_slectedNumberMaps.isNotEmpty) {
      List partsArray = _slectedNumberMaps[partIndex.toString()];
      if (partsArray.isNotEmpty) {
        for (Map element in partsArray) {
          int oldPartIndex = element['partIndex'];
          int oldIndex = element['index'];
          if (partIndex == oldPartIndex && index == oldIndex) {
            _numColor = rightNumColor;
            textColor = Colors.white;
          }
        }
      }
    }

    return GestureDetector(
        onTap: () {
          print('partIndex:$partIndex index:$index num:$num');
          var selectedItem = {
            'partIndex': partIndex,
            'index': index,
            'num': num
          };
          _selectedNumber(partIndex.toString(), selectedItem);
        },
        child: Container(
          height: cellH,
          width: cellW,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: bgColor,
            border: Border(
              bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
              right: BorderSide(color: HexColor('#dddddd'), width: 1),
            ),
          ),
          child: Container(
            width: 20,
            height: 20,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: _numColor,
              borderRadius: const BorderRadius.all(Radius.circular(20 * 0.5)),
            ),
            child: Text(
              num,
              style: TextStyle(
                fontWeight: FontWeight.w600,
                fontSize: 12,
                color: textColor,
              ),
            ),
          ),
        ));
  }
}
